package com.jiangyao.interceptor;


import com.jiangyao.common.constants.CacheConstants;
import com.jiangyao.common.constants.SystemConstants;
import com.jiangyao.common.exception.ServerException;
import com.jiangyao.common.utils.SpringBeanFactoryUtils;
import com.jiangyao.common.utils.StringUtils;
import com.jiangyao.component.RedisComponent;
import com.jiangyao.model.vo.UserSessionVO;
import com.jiangyao.service.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信拦截器
 * 主要用于微信公众号用户获取openid的信息，完成用户自动登录
 *
 * @author: yangyongchuan
 * @create: 2020年04月17日 10:23
 */
public class WeChatInterceptor implements HandlerInterceptor {

	private static final Logger LOGGER = LoggerFactory.getLogger(WeChatInterceptor.class);

	private static ConfigService configService;

	private static RedisComponent redisComponent;

	static {
		if (configService == null) {
			configService = SpringBeanFactoryUtils.getBean(ConfigService.class);
		}
		if (redisComponent == null) {
			redisComponent = SpringBeanFactoryUtils.getBean(RedisComponent.class);
		}
	}


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		// 从session 获取登录用户
		UserSessionVO userSessionVo = null;

		// 获取token，获取本地缓存登录信息
		String token = request.getHeader(SystemConstants.FRONTEND_LOGIN_TOKEN);
		if (StringUtils.isBlank(token)) {
			token = request.getParameter(SystemConstants.FRONTEND_LOGIN_TOKEN);
		}
		if (StringUtils.isNotBlank(token)) {
			userSessionVo = redisComponent.getObject(CacheConstants.CACHE_KEY_TOKEN_API_PREFIX + token);
		}
		if (userSessionVo == null || StringUtils.isBlank(userSessionVo.getOpenId())) {
			throw new ServerException(403, "微信用户未登录");
		}
		// 将登录用户信息放入request
		request.setAttribute("_userSession", userSessionVo);
		request.setAttribute("_openid", userSessionVo.getOpenId());
		request.setAttribute("_token", token);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

	}

}
